package com.su.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.su.usercenter.common.BaseResponse;
import com.su.usercenter.common.ErrorCode;
import com.su.usercenter.common.ResultUtils;
import com.su.usercenter.exception.BusinessException;
import com.su.usercenter.model.domain.User;
import com.su.usercenter.model.request.UserLoginRequest;
import com.su.usercenter.model.request.UserRegisterRequest;
import com.su.usercenter.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.stream.Collectors;

import static com.su.usercenter.constant.UserConstant.ADMIN;
import static com.su.usercenter.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 *
 * @author su
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     *
     * @return 用户id
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        String account = userRegisterRequest.getAccount();
        String password = userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(account, password, checkPassword,planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.Register(account, password, checkPassword, planetCode);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @return 用户id
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        String account = userLoginRequest.getAccount();
        String password = userLoginRequest.getPassword();
        if (StringUtils.isAnyBlank(account, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(account, password, request);
        return ResultUtils.success(user);
    }

    /**
     * 根据用户名查询用户
     * @param username
     * @return 用户列表
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUser(String username,HttpServletRequest request) {
        if(!isAdmin(request)){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);//不写val，默认表示模糊查询
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> result = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(result);
    }

    /**
     * 根据用户名id删除用户
     * @param id
     * @return 是否成功删除
     */
    @GetMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id,HttpServletRequest request) {
        if(!isAdmin(request) || id <= 0){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        boolean result = userService.removeById(id);//表示逻辑删除，即将isDelete字段更新为1
        return ResultUtils.success(result);
    }

    /**
     * 是否为管理员
     * @param request
     * @return
     */
    private boolean isAdmin(HttpServletRequest request){
        //鉴权
        //获取用户登录态
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if(user == null || user.getUserRole() != ADMIN){//要判断用户登录态是否为空，才能判断角色
            return false;
        }
        return true;
    }
    /**
     * 获取当前的用户
     */
    @GetMapping("/current")
    private BaseResponse<User> getCurrentUser(HttpServletRequest request){
        //获取用户登录态
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if(user == null ){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        //todo 用户校验
        Long id = user.getId();
        user = userService.getById(id);
        return ResultUtils.success(user);
    }
    /**
     * 用户登录
     *
     * @return 用户id
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> logout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        int result = userService.logout(request);
        return ResultUtils.success(result);
    }

}
